package com.rectcircle.scalatrateset.controller

import java.util.Date

import org.json4s.JsonDSL._
import org.json4s._
import org.scalatra.SessionSupport
import org.scalatra.atmosphere.{AtmoReceive, AtmosphereClient, AtmosphereSupport, ClientDisconnected, Connected, Disconnected, JsonMessage, ServerDisconnected, TextMessage}
import org.scalatra.json.{JValueResult, JacksonJsonSupport}

import scala.concurrent.ExecutionContext.Implicits.global

/**
  * @author Rectcircle
  *         createTime 2016/12/31
  */
class ChatController extends ScalatratestStack
  with JValueResult
  with JacksonJsonSupport with SessionSupport
  with AtmosphereSupport{
	
	implicit protected val jsonFormats: Formats = DefaultFormats
	
	atmosphere("/"){
		new AtmosphereClient {
			override def receive: AtmoReceive = {
				case Connected =>
					println("客户端 %s 已连接" format uuid)
					broadcast(("author" -> "Someone") ~ ("message" -> "joined the room") ~ ("time" -> (new Date().getTime.toString )), Everyone)
				case Disconnected(ClientDisconnected, _) =>
					broadcast(("author" -> "Someone") ~ ("message" -> "has left the room") ~ ("time" -> (new Date().getTime.toString )), Everyone)
				case Disconnected(ServerDisconnected, _) =>
					println("客户端 %s 已经断开连接" format uuid)
				case _: TextMessage =>
					send(("author" -> "system") ~ ("message" -> "Only json is allowed") ~ ("time" -> (new Date().getTime.toString )))
				case JsonMessage(json) =>
					println("收到了消息： %s ，来自 %s".format((json \ "message").extract[String], (json \ "author").extract[String]))
					val msg = json merge (("time" -> (new Date().getTime().toString)): JValue)
					broadcast(msg, Everyone)
			}
		}
	}
	
	
}
